// pages/qrcode.js
import drawQrcode from '../../static/qr/weapp.qrcode.esm.js'
import {
  ds
} from '../../tools/data';
import {
  ui
} from '../../tools/ui'

Page({
  data: {
    param: {},
    cloudPrefix: getApp().globalData.cloudPrefix
  },
  onLoad(options) {
    const {
      param,
      ex
    } = options
    this.setData({
      param: (param && JSON.parse(param)) || {},
      ex
    })
    // console.log(param, ex)
  },
  onShow() {
    const {
      param,
      ex
    } = this.data
    const {
      title,
      nickName
    } = param
    // console.log(param, ex)

    if (title == '推广') {
      this.showAdvQr()
    } else if (title == '我的用户码') {
      this.showQr({
        title,
        ex
      })
    } else if (title == '兑换码') {
      this.showQr({
        title,
        ex
      })
    } else if (title == '商家收款码') {

    } else {
      this.showQr(this.data.param)
    }
  },
  showAdvQr() {
    const {
      title
    } = this.data.param
    ds.cloudGetByOpenid('users', res => {
      // console.log(res)
      const user = res.result.data[0]
      this.setData({
        nickName: user.personInfo.nickName
      })
      this.showQr({
        title,
        staffOpenId: user._openid,
        nickName: user.personInfo.nickName
      })
    })
  },
  showQr(paramObj) {
    const text = JSON.stringify(paramObj)
    const query = wx.createSelectorQuery()
    query.select('#myQrcode')
      .fields({
        node: true,
        size: true
      })
      .exec((res) => {
        var canvas = res[0]?.node
        if (!canvas) return

        // 调用方法drawQrcode生成二维码
        drawQrcode({
          canvas: canvas,
          canvasId: 'myQrcode',
          width: 260,
          padding: 20,
          background: '#ffffff',
          foreground: '#000000',
          text // 包含的信息
        })
        ui.loading(false)

        // 获取临时路径
        // wx.canvasToTempFilePath({
        //   canvasId: 'myQrcode',
        //   canvas: canvas,
        //   x: 0,
        //   y: 0,
        //   width: 260,
        //   height: 260,
        //   destWidth: 260,
        //   destHeight: 260,
        //   success(res) {
        //     console.log('二维码临时路径：', res.tempFilePath)
        //   },
        //   fail(res) {
        //     console.error(res)
        //   }
        // })
      })
  }


})